package com.heny.demo.strategy;

import com.heny.demo.common.CommonErrorCode;
import com.heny.demo.common.CommonException;
import com.heny.demo.entity.TurnPointPOJO;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;
import java.util.Map;

public class FileProcessorContext {
    private FileProcessorStrategy strategy;

    private MultipartFile file;

    public void setStrategy(FileProcessorStrategy strategy) {
        this.strategy = strategy;
    }

    public void setFile(MultipartFile file) {
        this.file = file;
    }

    public FileProcessorContext(MultipartFile file) {
        this.file = file;

        String fileName = file.getOriginalFilename().toLowerCase();
        int dotIndex = fileName.lastIndexOf('.');
        if (dotIndex > 0 && dotIndex < fileName.length() - 1) {
            String fileType = fileName.substring(dotIndex + 1).toLowerCase();
            FileProcessorStrategyEnum strategyEnum = FileProcessorStrategyEnum.getByType(fileType);
            this.strategy = strategyEnum.getStrategy();
        } else {
            throw new CommonException(CommonErrorCode.PARAM_VALIDATION_FAILED, "不支持的文件类型");
        }
    }

    public List<TurnPointPOJO> execute() {
        if (strategy == null) {
            throw new CommonException(CommonErrorCode.SYSTEM_ERROR, "strategy is null");
        }
        return strategy.processFile(this.file);
    }

}